var showMessage = function (options) {
    var settings = {
        icon: 'fa fa-info-circle',
        title: '',
        message: '',
        type: 'info',
        delay: 3000
    };

    if (typeof options === "string") {
        settings.message = options;
    } else {
        settings = $.extend(settings, options || {});
        settings.title=options.title?options.title:options.status;
        (options.status.toLowerCase()==="error") ?settings.type='danger':settings.type='info';
    }

    $.notify({
        title: settings.title,
        message: settings.message,
        'z_index': 9999
    }, {
        type: 'pastel-' + settings.type,
        delay: settings.delay,
        template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
        '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
        '<span data-notify="title">{1}</span>' +
        '<span data-notify="message">{2}</span>' +
        '</div>'
    });
};

createPathNav = function (folders, folder) {
    var str = '<li><a href="javascript:;">根目录</a></li>';
    for (var i = 0; i < folders.length; i++) {
        if (folders[i])
            str += '<li><a href="javascript:;" data-folder="' + folders[i] + '">' + folders[i] + '</a></li>';
    }
    if (folder)
        str += '<li class="active">' + folder + '</a></li>';
    $('ol.breadcrumb').html(str);
}

var dialog=function(settings) {
    settings=$.extend({
        'type': 'info',
        'size': 'wide',
        'title': '',
        'url':''
    }, settings || {});

    Dialog.show({
        id: 'modal_ajax',
        type: 'type-'+settings.type,
        size: 'size-'+settings.size,
        title: settings.title,
        message: $('<div></div>').load(settings.url,function(response,status,xhr){
            if (xhr.status==404) {
                $(this).html('<div class="wrap">'+
                    '<h1>404 - File Not Found</h1>'+
                    '<p>Controller or page is not found. </p>'+
                    '<p>当前模块或页面未找到，请联系管理员。</p>'+
                    '</div>');
            } else if (xhr.status==500) {
                $(this).load('<div class="wrap">'+
                    '<h1>500 - Have an Error</h1>'+
                    '<p> </p>'+
                    '<p>当前服务器发生错误，请联系管理员。</p>'+
                    '</div>');
            }
        })
    });
};

dialog.close=function() {
    $('#modal_ajax').modal('hide').remove();
};


store = function () {
    if (typeof (arguments[0]) == 'object') {
        arguments[0].each(function (name, val) {
            localStorage.setItem(name, val);
        })
    } else if (arguments[1]) {
        localStorage.setItem(arguments[0], arguments[1]);
    } else {
        return localStorage.getItem(arguments[0]);
    }
}

function listCategory() {
    if ($(window).width() < 748) {
        var dropdown;
        if ($('#categoryList').find('li.category-list').length <1) {
            dropdown = $('<li class="dropdown category-list"></li>')
                .append('<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-menu"></i> </a>')
                .append('<ul class="dropdown-menu" role="menu"></ul>');
        } else {
            dropdown=$('.navbar-custom-menu .navbar-nav').children('.category-list').show();
        }

        $('#categoryList').hide().find('li').each(function () {
            dropdown.children('ul').append($(this));
        });
        $('.navbar-custom-menu .navbar-nav').prepend(dropdown);
    } else {
        $('.category-list ul.dropdown-menu').find('li').each(function () {
            $('#categoryList').show().append($(this));
        });
        $('.category-list').hide();
    }
}

$(function () {
    $(document).on('click','[data-dialog]',function () {
        var url=$(this).data('dialog');
        var title=$(this).attr('title')?$(this).attr('title'):$(this).data('original-title');
        dialog({title:title,url:url});
    })
});

createForm = function (options) {
    var option = $.extend(true, {
        'id': 'dialogForm',
        'form': {
            'name': 'form',
            'id': 'dialogInput',
            'method': 'post',
            'action': '',
            'use': true,
            'class': 'form-horizontal'
        },
        'input': [],
        'submit': {
            'label': '确定',
            'icon': 'fa fa-check',
            'action': function () {
            }
        },
        'cancel': {
            'label': '取消',
            'icon': 'fa fa-close',

        }
    }, options || {});

    if (option.form.use) {
        var message = $('<form>', {
            class: option.form.class,
            method: option.form.method,
            name: option.form.name,
            id: option.form.id,
            action: option.form.action
        });
    } else {
        var message= $('<div>',{
            class: option.form.class,
            id: option.form.id
        })
    }

    $.each(option.input, function (key, input) {
        var div = '';
        var str = (input.type==='button')?$('<button>'):$('<div>', {'class': (input.type==='hidden')?'hide':'form-group'});
        if (input.label) {
            str.append($('<label class="col-sm-2 control-label">' + input.label + '</label>'));
            div = 'col-sm-10';
        }
        switch (input.type) {
            case 'textarea':
                str.append($('<div>', {'class': div}).append(
                    $('<textarea>', {
                        class: "form-control",
                        placeholder: input.placeholder,
                        id: input.id,
                        html:input.value
                    })));
                break;
            case 'select':
                var select = $('<div>', {class: div}).append(
                    $('<select>', {
                        class: "form-control",
                        name: input.name,
                        id: input.id
                    }));
                if (input.options.length > 0)
                    $.each(input.options, function (k, option) {
                        select.children('select').append($('<option>', {
                            value: option.value,
                            selected: option.selected,
                            html: option.name
                        }));
                    });
                str.append(select);
                break;
            case 'button':
                str.attr({
                    class: 'btn '+(input.class?input.class:'btn-default'),
                    type: 'button',
                    name: input.name,
                    id:input.id
                }).append($('<i>',{class:input.icon})).html(input.label);
                break;
            default:
                str.append($('<div>', {'class': div}).append(
                    $('<input>', {
                        class: "form-control",
                        type: input.type,
                        name: input.name,
                        placeholder: input.placeholder,
                        id: input.id,
                        value: input.value,
                        'data-required':input.required
                    })));
                break;
        }
        message.append(str);
    });

    return message;
};

DialogInput = function (options) {
    var option = $.extend(true, {
        'title': 'INPUT',
        'id': 'dialogForm',
        'form': {
            'name': 'form',
            'id': 'dialogInput',
            'method': 'post',
            'action': '',
            'class': 'form-horizontal'
        },
        'input': [],
        'submit': {
            'label': '确定',
            'icon': 'fa fa-check',
            'action': function () {
            }
        },
        'cancel': {
            'label': '取消',
            'icon': 'fa fa-close',

        }
    }, options || {});

    var message=createForm(option);

    var dialog=Dialog.show({
        title: option.title,
        message: message,
        id:option.id,
        closable:true,
        buttons: [{
            label: option.submit.label,
            icon: option.submit.icon,
            cssClass: 'btn-primary',
            hotkey: 13,
            action: function () {
                $('#' + option.form.id).submit();
            }
        }, {
            label: option.cancel.label,
            icon: option.cancel.icon,
            cssClass: 'btn-default',
            hotkey: 27,
            action: function (dialogRef) {
                if (typeof option.cancel.action === "function") option.cancel.action();
                dialog.close();
            }
        }]
    });

    $(document).on('submit','#'+ option.form.id,function (e) {
        e.preventDefault();
        var $this=$(this);
        $this.formValidator({
            sending: {
                type: 'ajax',
                success: function (data) {
                    var e = $.parseJSON(data);
                    showMessage(e);
                    if (e.status !== "Error") {
                        $this.remove();
                        if (typeof option.submit.action === "function") option.submit.action();
                        dialog.close();
                    }
                },
                error: function () {
                    showMessage("提交失败！");
                }
            }
        });
    });
};